#!/bin/bash

# ============================================
# 简化方案：移除 frontend.conf 中的 default_server
# ============================================

echo "=== 恢复主配置文件 ==="
sudo cp /etc/nginx/nginx.conf.backup /etc/nginx/nginx.conf

echo ""
echo "=== 修改 frontend.conf，移除 default_server ==="
sudo tee /etc/nginx/conf.d/frontend.conf > /dev/null << 'EOF'
server {
    listen 80;
    listen [::]:80;
    server_name 10.170.129.4;
    
    root /mnt/lwy/django-vue3-admin/web/dist;
    index index.html;
    
    access_log /var/log/nginx/frontend_access.log;
    error_log /var/log/nginx/frontend_error.log;
    
    client_max_body_size 100M;
    
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/x-javascript application/xml+rss application/xhtml+xml image/svg+xml;
    
    # API 代理配置（必须在 location / 之前）
    location /api/ {
        proxy_pass http://127.0.0.1:8000/api/;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_connect_timeout 600s;
        proxy_read_timeout 600s;
        proxy_send_timeout 600s;
        proxy_buffering off;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
        client_max_body_size 100M;
    }
    
    # 前端路由配置
    location / {
        try_files $uri $uri/ /index.html;
        
        if ($request_uri ~* "^/$|^/index.html|^/index.htm") {
            add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate";
            add_header Pragma "no-cache";
            expires -1;
        }
        
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|otf)$ {
            expires 7d;
            add_header Cache-Control "public, immutable";
            access_log off;
        }
    }
    
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }
}
EOF

echo ""
echo "=== 验证配置 ==="
sudo nginx -t

echo ""
echo "=== 重启 Nginx ==="
sudo systemctl restart nginx

echo ""
echo "=== 测试 ==="
sleep 1
echo "测试通过 IP 访问："
curl -v -H "Host: 10.170.129.4" http://127.0.0.1/api/login/ 2>&1 | head -20

echo ""
echo "如果通过 IP 访问不行，请使用："
echo "  curl http://10.170.129.4/api/login/"

